import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { Row, Avatar, Card, Col, Table, message, Tooltip, Statistic, Button, Input, Collapse } from 'antd';
import { css } from '@emotion/css';
import { ArrowUpOutlined, CopyOutlined, DislikeOutlined, FontSizeOutlined, LikeOutlined, ReloadOutlined, SoundOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import "highlight.js/styles/atom-one-dark.css";
import ChartCore from 'node_modules/react-echarts-core';
import { get, post } from '@/service/axiosManager';
import Title from 'antd/es/typography/Title';
import { TitleComponent } from 'echarts/components'
import { random } from 'lodash';
import CueWordsDialog from './words/CueWordsDialog';
import EchatComponent from './EchatComponent';
import { UtilHelpers } from '@/service/general/utils/utilHelpers';
import { MCPItemType } from '@/service/general/enumType';
import { CheckBoxSvg } from './assets/CustomizeSvg';
import { McpItem } from '@/service/request/modal/dataModal';
import { PlayBookMcp } from './chat/chattype/PlayBookMcp';
import { PlayBook } from './chat/chattype/PlayBook';

const messageStyles = {
  left: css`
    margin-left: 10px;
    &::before {
      content: '';
      position: absolute;
      top: 15px;
      left: -10px;
      border-width: 2px 10px 10px 0;
      border-style: solid;
      border-color: transparent #ffffff transparent transparent;
    }
  `,
  right: css`
    margin-right: 10px;
    &::before {
      content: '';
      position: absolute;
      top: 15px;
      right: -10px;
      border-width: 10px 10px 0;
      border-style: solid;
      border-color: #ffffff transparent transparent transparent;
      transform: rotate(-90deg);
    }
  `,
};



export default function ContentMsg({ msgContent, contentId = '', onTypingComplete, onResendMsgComplete, onConfirmMsgComplete, onUpdateMsgContent,onScrollToBottom }: { msgContent: any[], contentId: string, onTypingComplete: () => void, onResendMsgComplete: (msg: string) => void, onConfirmMsgComplete: (msgId: number) => void, onUpdateMsgContent: (newContent: any[]) => void ,onScrollToBottom: (msgContent: HTMLDivElement) => void}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [processName, setProcessName] = useState('');
  const [processParam, setProcessParam] = useState('');
  const [isButtonDisabled, setIsButtonDisabled] = useState<{ [key: number]: boolean }>({});

  const [displayedText, setDisplayedText] = useState<string>('');
  const [cueOpen,setCueOpen] = useState<boolean>(false);
  const [cueWord,setCueWords] = useState<{
    title: string,
    words: string,
    command: string,
  } | null>(null);
  const lastItem = msgContent.filter((item) => item.id === contentId)?.[0];

  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
      // console.log("click:\n ", containerRef.current.scrollTop);
      onScrollToBottom(containerRef.current);
    }

    if (lastItem?.needConfirm === true) {
      // const { host, net } = JSON.parse(lastItem.processParam);
      let defaultParam = lastItem.processParam;

      // if (lastItem.processName === '防火墙快速封禁流程' || lastItem.processName === 'tsic-unprohibition流程') {
      //   defaultParam = host;
      // } else if (lastItem.processName === '内网核心资产梳理') {
      //   defaultParam = net;
      // }

      setProcessParam(defaultParam);
      setProcessName(lastItem.processName);
    }

    if (lastItem?.answerType === 'text') {
      let frameId: number | null = null;
      let currentText = '';
      let charIndex = 0;

      const typeWriter = () => {
        if (charIndex < lastItem?.answer?.length) {
          const charsToAdd = Math.floor(Math.random() * 7) + 2;
          const nextCharIndex = Math.min(charIndex + charsToAdd, lastItem?.answer?.length);
          currentText += lastItem.answer.slice(charIndex, nextCharIndex);
          setDisplayedText(currentText);
          charIndex = nextCharIndex;
          frameId = requestAnimationFrame(typeWriter);
        } else {
          if (frameId) {
            cancelAnimationFrame(frameId);
            frameId = null;
          }
          onTypingComplete();
        }
      };

      frameId = requestAnimationFrame(typeWriter);

      return () => {
        if (frameId) {
          cancelAnimationFrame(frameId);
        }
      };
    } else {
      onTypingComplete();
    }
  }, [lastItem, onTypingComplete, msgContent]);

  const confirmMsg = (msgId: number) => {
    setIsButtonDisabled(prev => ({ ...prev, [msgId]: true }));
    post('/ai/chat/process/confirm', {
      conversationMessageId: msgId,
      processName: processName,
      processParam: processParam
    }).then((res) => {
      console.log(res);
      onConfirmMsgComplete(msgId);
      getProcessStatus(msgId);
    });
  }

  const getProcessStatus = (msgDetailId: number) => {
    const fetchStatus = () => {
      get('/ai/chat/qa/message/' + msgDetailId).then((res: any) => {
        if (res.result.answerType === 'playbook' || res.result.answerType === 'playbookmcp' || res.result.answerType === 'process') {
          const timeoutId = setTimeout(fetchStatus, 5000);
          UtilHelpers.RecordTimeoutId("Process-msg", timeoutId);
        }
        onUpdateMsgContent(res.result);
      });
    };
    fetchStatus();
  }

  return (
    <div
      ref={containerRef}
      style={{
        overflowY: 'scroll',
        maxHeight: '100%',
        scrollbarWidth: 'none', // 对于 Firefox
        msOverflowStyle: 'none', // 对于 Internet Explorer 和 Edge
      }}
      className={css`
        &::-webkit-scrollbar {
          display: none; // 对于 Chrome, Safari 和 Opera
        }
      `}
    >
      {msgContent.map((item: any, index: number) => (
        <React.Fragment key={item.id + '-' + index}>
          <Row
            key={"msg-" + item.id + "-" + index + "-001"}
            justify='end'//{item.align === 'right' ? 'end' : 'start'}
            style={{ marginBottom: 16 }}
          >
            <Col span={24}>
              <div style={{
                display: 'flex',
                flexDirection: 'row-reverse',//item.align === 'right' ? 'row-reverse' : 'row',
                alignItems: 'flex-start',
              }}>
                <Avatar src="/me01.png" size={40} />
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
                  <Card
                    style={{ maxWidth: 600, position: 'relative', textAlign: 'left' }}
                    hoverable={true}
                    className={messageStyles.right}
                  >
                    <ReactMarkdown rehypePlugins={[rehypeHighlight]} className="prose prose-zinc max-w-none dark:prose-invert">
                      {item.question}
                    </ReactMarkdown>
                  </Card>
                  <div style={{ width: '100%', textAlign: 'right', paddingLeft: '0px', paddingRight: '10px' }}>
                    {/* <SoundOutlined style={{ margin: 5 }} /> */}
                    <Tooltip title="提词">
                      <FontSizeOutlined style={{ margin: 5 }} onClick={() => {
                        // console.log(item.question);
                        const word = item.question;
                        const cueWord = {
                          "title": word,
                          "words": word,
                          "command": word,
                        }
                        setCueWords(cueWord);
                        setCueOpen(true);
                      }} />
                    </Tooltip>
                    <Tooltip title="复制">
                      <CopyOutlined style={{ margin: 5 }} onClick={() => {
                        message.success('已复制到剪贴板');
                        navigator.clipboard.writeText(item.question);
                      }} />
                    </Tooltip>
                    <Tooltip title="重新发送">
                      <ReloadOutlined style={{ margin: 5 }} onClick={() => {
                        onResendMsgComplete(item.question);
                      }} />
                    </Tooltip>
                    {/* <LikeOutlined style={{ margin: 5 }} />
                    <DislikeOutlined style={{ margin: 5 }} /> */}
                    <CueWordsDialog open={cueOpen} data={cueWord} setOpen={setCueOpen}></CueWordsDialog>
                  </div>
                </div>
              </div>
            </Col>
            <Col span={24} />
          </Row>
          {
            item.key == '-1000' && (
              <Row
                key={"msg-" + item.id + "-" + index + "-002"}
                justify='start'//{item.align === 'right' ? 'end' : 'start'}
                style={{ marginBottom: 16 }}
              >
                <Col span={24}>
                  <div style={{
                    display: 'flex',
                    flexDirection: 'row',//item.align === 'right' ? 'row-reverse' : 'row',
                    alignItems: 'flex-start',
                  }}>
                    <Avatar src="/logo.png" size={40} />
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
                      <Card loading
                        style={{ width: 200, height: 40, position: 'relative', textAlign: 'left' }}
                        hoverable={true}
                        className={messageStyles.left}
                      >
                      </Card>
                    </div>
                  </div>
                </Col>
              </Row>
            )

          }
          {
            (item.answer || item.answer == '-9999') && (
              <Row
                key={"msg-" + item.id + "-" + index + "-003"}
                justify='start'//{item.align === 'right' ? 'end' : 'start'}
                style={{ marginBottom: 16 }}
              >
                <Col span={24}>
                  <div style={{
                    display: 'flex',
                    flexDirection: 'row',//item.align === 'right' ? 'row-reverse' : 'row',
                    alignItems: 'flex-start',
                  }}>
                    <Avatar src="/logo.png" size={40} />
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
                      <Card
                        style={{ maxWidth: 600, position: 'relative', textAlign: 'left' }}
                        hoverable={true}
                        className={messageStyles.left}
                      >
                        {item.answerType == 'text' && (
                          <ReactMarkdown
                            rehypePlugins={[rehypeHighlight]}
                            className={css`
                              pre {
                                overflow-x: auto;
                                white-space: pre-wrap;
                                word-wrap: break-word;
                                max-width: 100%;
                              }
                              code {
                                white-space: pre-wrap;
                                word-wrap: break-word;
                              }
                            `}
                          >
                            {item.id === contentId ? displayedText : item.answer}
                          </ReactMarkdown>
                        )}
                        {item.answerType == 'table' && (
                          (() => {
                            try {
                              const jsonData = item.answer ? JSON.parse(item.answer).slice(0, 30) : [];
                              const headers = Object.keys(jsonData[0] || {});
                              return (
                                <>
                                  <div style={{ overflowX: 'auto', maxWidth: '700px' }}>
                                    <Table
                                      dataSource={jsonData.map((data: any, index: any) => ({ ...data, key: index }))} // 为每条数据添加唯一的 key
                                      columns={headers.map((header: any, index: any) => ({
                                        title: header,
                                        dataIndex: header,
                                        key: header + index, // 确保列的 key 也是唯一的
                                        ellipsis: true,
                                      }))}
                                      pagination={false}
                                      size="small"
                                      scroll={{ x: true }}
                                    />
                                  </div>
                                  {jsonData.length >= 30 && (<span className="text-gray-500 text-sm">数据量过大，已截取前30条</span>)}
                                </>
                              );
                            } catch (error) {
                              console.error('解析JSON数据时出错:', error);
                              return <div>数据格式错误（请尝试修改问题，再次提问）</div>;
                            }
                          })()
                        )}
                        {
                          item.answerType == 'playbook' && (
                            () => {
                              return (<>
                                <div>
                                  {item.needConfirm == true && (
                                    <div>
                                      <Input
                                        value={processName}
                                        style={{ margin: '5px' }}
                                        onChange={(e) => setProcessName(e.target.value)}
                                      />
                                      {/* <Input
                                        value={processParam}
                                        style={{ margin: '5px' }}
                                        onChange={(e) => setProcessParam(e.target.value)} 
                                      /> */}
                                      <PlayBook data={item.processParam} setProcessParam={setProcessParam} />
                                      <Button 
                                        type="primary" 
                                        disabled={isButtonDisabled[item.id]} 
                                        onClick={() => confirmMsg(item.id)}
                                      >
                                        执行
                                      </Button>
                                    </div>
                                  )}
                                  {item.needConfirm != true && (
                                    <ReactMarkdown>{item.id === contentId ? displayedText : item.answer}</ReactMarkdown>
                                  )}
                                </div>
                              </>)
                            }
                          )()
                        }
                        {
                          item.answerType == 'playbookmcp' && (
                            () => {
                              let mcpStr: McpItem[] = [];
                              if (item.processParam && item.processParam.length > 0 && item.processParam !== "") {
                                mcpStr = JSON.parse(item.processParam);
                              }
                              return (<>
                                <div>
                                  {item.needConfirm == true && (
                                    <div className="w-full flex flex-col items-start justify-center gap-2">
                                      <div className="w-full flex flex-col items-start justify-center gap-1">
                                        <div className="w-96 h-11 flex flex-row items-center justify-center rounded-lg border p-2 has-[input:focus-within]:border-blue-500/60">
                                          <input 
                                          value={processName} 
                                          className="w-full h-full border-none outline-none"
                                          onChange={(e) => setProcessName(e.target.value)} />
                                        </div>
                                        {
                                          mcpStr.length > 0 ? (<>
                                            <PlayBookMcp data={mcpStr} setProcessParam={setProcessParam} />
                                          </>):(<>
                                            <div className="w-96 h-11 flex flex-row items-center justify-center rounded-lg border p-2 has-[input:focus-within]:border-blue-500/60">
                                              <input 
                                              value={processParam} 
                                              className="w-full h-full border-none outline-none"
                                              onChange={(e) => setProcessParam(e.target.value)} />
                                            </div>
                                          </>)
                                        }
                                      </div>
                                      <div className="w-full">
                                        <Button 
                                          type="primary" 
                                          disabled={isButtonDisabled[item.id]} 
                                          onClick={() => confirmMsg(item.id)}
                                        >
                                          执行
                                        </Button>
                                      </div>
                                      {/* <Input
                                        value={processName}
                                        style={{ margin: '5px' }}
                                        onChange={(e) => setProcessName(e.target.value)}
                                      />
                                      <Input
                                        value={processParam}
                                        style={{ margin: '5px' }}
                                        onChange={(e) => setProcessParam(e.target.value)} 
                                      /> */}
                                    </div>
                                  )}
                                  {item.needConfirm != true && (
                                    <ReactMarkdown>{item.id === contentId ? displayedText : item.answer}</ReactMarkdown>
                                  )}
                                </div>
                              </>)
                            }
                          )()
                        }
                        {
                          item.answerType == 'process' && (() => {
                            return UtilHelpers.isJsonFormat(item.answer) ? (() => {
                              const jsonData = item.answer ? JSON.parse(item.answer): [];
                              return (<>
                              <Title level={4}>{jsonData.status == "3" ? "执行成功" : (jsonData.status == "4" ? "执行失败" : "执行异常")}</Title>
                              <Collapse accordion items={
                                jsonData.data.map((e: any) => {
                                  return {
                                    key: e.actId,
                                    label: e.actName,
                                    children: <div>
                                      <div>能力名称：{e.actName}</div>
                                      <div>开始时间：{e.startTime}</div>
                                      <div>结束时间：{e.endTime}</div>
                                      <div>状态：{e.execStatus == '3' ? '成功' : '失败'}</div>
                                      <div>结果：{e.content}</div>
                                      </div>
                                      }
                                    })
                                    } />
                              </>);
                            })():(<>
                              <div>{item.answer}</div>
                            </>);
                          //     retrun UtilHelpers.isJsonFormat(item.answer) ? (() => {
                          //       const jsonData = item.answer ? () => JSON.parse(item.answer): [];
                          //       return (<>
                          //       <Title level={4}>{jsonData.status == "3" ? "执行成功" : (jsonData.status == "4" ? "执行失败" : "执行异常")}</Title>
                          //       <Collapse accordion items={
                          //         jsonData.data.map((e: any) => {
                          //           return {
                          //             key: e.actId,
                          //             label: e.actName,
                          //             children: <div>
                          //               <div>能力名称：{e.actName}</div>
                          //               <div>开始时间：{e.startTime}</div>
                          //               <div>结束时间：{e.endTime}</div>
                          //               <div>状态：{e.execStatus == '3' ? '成功' : '失败'}</div>
                          //               <div>结果：{e.content}</div>
                          //             </div>
                          //           }
                          //         })
                          //       } />
                          //       {/* <div>
                          //         {jsonData.data.map((e: any) => {
                          //           return (<div>{e.actName}</div>)
                          //         })} 
                          //       </div> */}
                          //     </>)
                          //   }):(() => {
                          //     return (<>
                          //       <div></div>
                          //     </>)
                          //   })
                          // })
                          })()
                        }
                        {
                          item.answerType == 'chart' && (
                            (() => {
                              try {
                                const jdata = item.playbookResult || item.answer;
                                if (UtilHelpers.isJsonFormat(jdata)) {
                                  console.log("is json: \n", jdata);
                                  const jsonData = item.answer ? JSON.parse(jdata) : [];
                                  return <EchatComponent jsonData={jsonData} />;
                                } else {
                                  return <ReactMarkdown
                                    rehypePlugins={[rehypeHighlight]}
                                    className={css`
                                      pre {
                                        overflow-x: auto;
                                        white-space: pre-wrap;
                                        word-wrap: break-word;
                                        max-width: 100%;
                                      }
                                      code {
                                        white-space: pre-wrap;
                                        word-wrap: break-word;
                                      }
                                    `}
                                  >
                                    {item.id === contentId ? displayedText : jdata}
                                  </ReactMarkdown>
                                }
                                
                              } catch (error) {
                                console.error('解析JSON数据时出错:', error);
                                return <div>数据格式错误（请尝试修改问题，再次提问）</div>;
                              }
                            })()
                          )
                        }
                      </Card>
                      <div style={{ width: '100%', textAlign: 'left', paddingLeft: '10px', paddingRight: '0px' }}>
                        {/* <SoundOutlined style={{ margin: 5 }} /> */}
                        <Tooltip title="复制">
                          <CopyOutlined style={{ margin: 5 }} onClick={() => {
                            message.success('已复制到剪贴板');
                            navigator.clipboard.writeText(item.answer);
                          }} />
                        </Tooltip>
                        {/* <Tooltip title="重新发送">
                          <ReloadOutlined style={{ margin: 5 }} onClick={() => {
                            onResendMsgComplete(item.question);
                          }} />
                        </Tooltip> */}
                        {/* <LikeOutlined style={{ margin: 5 }} />
                        <DislikeOutlined style={{ margin: 5 }} /> */}
                      </div>
                    </div>
                  </div>
                </Col>
                <Col span={24} />
              </Row>
            )
          }
        </React.Fragment>
      ))}
      <style>{`
        .ant-card-body {
          padding: 10px !important;
        }
      `}</style>
    </div>
  );
}